package com.nd.mobile.study.view;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import com.nd.mobile.study.R;
import com.nd.mobile.study.common.BaseActivity;
import com.nd.mobile.study.common.constants.BundleConstants;
import com.nd.mobile.study.common.constants.FlagConstants;
import com.nd.mobile.study.common.util.ExceptionHandler;
import com.nd.mobile.study.common.util.L;
import com.nd.mobile.study.common.util.StringUtils;
import com.nd.mobile.study.domain.User;

public class LoginLoadingActivity extends BaseActivity {

	public static final String	TAG			= "LoginLoadingActivity";

	private String				username	= null;

	private String				password	= null;

	@Override
	protected void onBaseCreate(Bundle savedInstanceState) {
		setContentView(R.layout.login_loading);
	}

	@Override
	protected void onAfterCreate(Bundle savedInstanceStat) {
	}

	@Override
	protected void initViews() {
	}

	@Override
	protected void onResume() {
		login();
		super.onResume();
	}

	/**
	 * 登陆事件
	 */
	private void login() {
		// 1.获取用户名和密码
		Bundle bundle = getIntent().getExtras();
		username = bundle.getString(BundleConstants.LOGIN_USERNAME);
		password = bundle.getString(BundleConstants.LOGIN_PASSWORD);

		LoginTask task = new LoginTask();
        task.execute(new String[]{username,password});
	}

	class LoginTask extends AsyncTask<String, Integer, User> {
		private String	errorMsg;

		@Override
		protected User doInBackground(String... params) {
			String username = params[0];
			String password = params[1];
			try {
				User.login(mApp, username, password);
			} catch (Exception e) {
				L.e(TAG, e.getMessage());
				errorMsg = ExceptionHandler.parseExceptionInfo(e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(User result) {
			super.onPostExecute(result);
			LoginLoadingActivity.this.loginHandle(errorMsg);
		}
	}

	/**
	 * 接收到登陆的数据后，做相应的处理
	 * 
	 * @param msg
	 */
	private void loginHandle(String errorMsg) {
		// 1.获取返回的数据，并检查
		if (!StringUtils.isEmpty(errorMsg)) {
			toLoginActivity(errorMsg);
			return;
		}

		// 保存登陆数据至shared文件中
		User.saveUserInfoIntoSharedPreferences(mApp, username, password);

		// 登陆，进入主界面
		Intent intent = new Intent();
		intent.setClass(this, TabMainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
	}

	/**
	 * 页面跳转至登陆界面
	 * 
	 * @param res
	 */
	public void toLoginActivity(String res) {
		Intent intent = new Intent();
		intent.setClass(this, LoginActivity.class);
		intent.putExtra(FlagConstants.LOGIN_FLAG_LOGIN_ERROR, res);
		startActivity(intent);
		finish();
	}

}
